<?php

	ini_set('display_errors', 1);
	error_reporting(E_ALL | E_STRICT);
	set_time_limit(60*60);
	ini_set('memory_limit', '128M');
	date_default_timezone_set('America/New_York');
	
	require_once "config.php";
	require_once dirname(__FILE__). '/util/connection.class.php';
	require_once dirname(__FILE__). '/util/record.php';
	
	$time = time();
	$dirname = RAW_DATA_ROOT.'/'. date('Y_m', $time);
	$filename = $dirname.'/'.date('d_H',$time).'_recovery';

	if (!file_exists($dirname))
	{
		mkdir($dirname, 0600, true);
	}
	$file = fopen($filename, "w+");
	
	$dbconn = Connection::getInstance();
	
	$users = getUsers($dbconn);
	//$users = array(array('id'=>1,'domain'=>'lalaloot.com', 'site_name'=>'lalaloot.com', 'firstname'=>'test', 'email'=>'devin@test.com', 'template'=>'lalaloot.com'),
	//array('id'=>2,'domain'=>'lalaloot.com', 'site_name'=>'lalaloot.com', 'firstname'=>'test', 'email'=>'devin@test.com', 'template'=>'lalaloot.com'));
	foreach ($users as $user){
		fwrite($file, $user['id'] . ':' . $user['won'] . ':' . $user['monthly'] . ':' . $user['credit'] . ':' . $user['played'] . ':' . $user['monthly_played'] . ':' . $user['site_id'] . "\n");
		if (updateUserProfile($user['id'], $user['domain'], $dbconn, $file))
			addNewEmail('revoke', $user['id'], $user['template'], $user['domain'], $user['site_name'], array('firstname'=>$user['firstname'], 'email'=>$user['email'], 'uid'=>$user['id']), $dbconn, $file);
			
	}
	
	
	
	function updateUserProfile($uid, $domain, Connection $db, $file)
	{
		if ($domain == 'lalaloot.com')
			$sql = "update `users` set credit=25, won=won-monthly+5, played=played-monthly_played+5, balance=won, daily_played=0, weekly_played=0, daily=0, weekly=0, monthly=0, monthly_played=0 WHERE id=?";
		else 
			$sql = "update `users` set credit=5, won=won-monthly+5, played=played-monthly_played+5, balance=won, daily_played=0, weekly_played=0, daily=0, weekly=0, monthly=0, monthly_played=0 WHERE id=?";
		try{
			$result =  $db->execute($sql, array($uid));
			if ($result) {
				fwrite($file, $uid . ':' . $domain . ':profile:1' .  "\n");
			}
			else{
				fwrite($file, $uid . ':' . $domain . ':profile:0' .  "\n");
			}
			return $result;
		}catch (Exception $e){
			fwrite($file, $uid . ':' . $domain . ':profile:2'.  "\n");
			//fwrite($file, $e->getMessage());
		}
	}
	
	function getUsers(Connection $db)
	{
		$sql = "select u.id as id, u.firstname as firstname , u.won as won, u.monthly as monthly, u.credit as credit, u.played as played, u.monthly_played as monthly_played, u.site_id as site_id, u.email as email, s.domain as domain, s.name as site_name , s.template as template from users as u, sites as s where u.created>=1319688000 and u.created<1320120000 and u.monthly>0 and (u.last_visit<1320120000 or u.last_visit>1320166800) and u.won>11 and u.monthly>=3 and u.id!=54873 and u.id!=57033 and u.id!=57380 and u.id!= 57194 and u.id!=55719 and u.site_id=s.id order by u.monthly desc";
		try{
			return $db->query($sql);
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	


	function getTemplate($tag, $site_template)
	{
		$template_name = TEMPLATE_ROOT .'/'.$site_template . '/email/' . $tag . '.html';
		if(file_exists($template_name))
		{
			if(is_readable($template_name))
			{
				$template = file_get_contents($template_name);
				return $template;
			}
		}
	}
	
	function addNewEmail($tag, $uid, $site_template, $domain, $sitename, $args, $db, $file)
	{
		if($template = getTemplate($tag, $site_template))
		{
			$content = translate($template,  $args);
			if(addSentEmailToDb($uid, $sitename, 'no-reply@' . strtolower($domain), $args['email'], $content, 50, $db, $file))
			{
				fwrite($file, $uid . ':' . $domain . ':email:1'.  "\n");
				$record = new Record($args['uid']);
				$record->addEmailSentRecording($tag);
				return true;
			}
		}
		fwrite($file, $uid . ':' . $domain . ':email:0'.  "\n");
		return false;		
	}
	
	function addSentEmailToDb($uid, $sender, $sendfrom, $sendto, $content, $priority,  Connection $db, $file){
		$sql = "insert into emails set sender=?, sendfrom=?, subject=?, sendto=?, content=?, created=?, sent=?, priority=?, email_type=?";
		try{
			return $db->execute($sql,array($sender, $sendfrom, 'Account Update - Game Malfunction', $sendto, $content, time(), 0, $priority, 'revoke'));
		}catch (Exception $e){
			fwrite($file, $uid . ':' . $sender . ':email:2'.  "\n");
		}
	}
	
	function translate($content, $args){
		foreach ($args as $k => $v){
			$content = str_replace('[[' . $k . ']]', $v, $content);
		}
		return $content;
	}